package com.kepler.social.domain.user.account;

import com.kepler.social.common.utils.DateTimeUtil;
import com.kepler.social.common.utils.ReflectionUtil;
import com.kepler.social.user.dao.domain.UserInfo;
import com.kepler.social.user.dao.domain.UserSocialInfo;
import com.kepler.social.user.dao.mapper.UserInfoMapper;
import com.kepler.social.user.dao.mapper.UserSocialInfoMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.Objects;

@Repository
public class UserAccountRepository {

    @Resource
    private UserInfoMapper userInfoMapper;
    @Resource
    private UserSocialInfoMapper userSocialInfoMapper;

    public UserAccountAggregate findByUserId(Long userId) {
        assert userId != null;
        UserInfo userInfo = userInfoMapper.selectByPrimaryKey(userId);
        UserSocialInfo userSocialInfo = userSocialInfoMapper.selectByPrimaryKey(userId);
        return new UserAccountAggregate(userInfo, userSocialInfo);
    }

    public void create(UserAccountAggregate aggregate) {
        aggregate.checkExist();
        userInfoMapper.insertSelective(aggregate.getRoot());
        userSocialInfoMapper.insertSelective(aggregate.getSocialInfo());
    }

    public void updateSingleFiled(String fieldName, Object fieldVal, Long userId) {
        assert Objects.nonNull(userId);
        assert Objects.nonNull(fieldVal);
        UserInfo root = ReflectionUtil.checkAndSetFieldValue(UserInfo.class, fieldName, fieldVal);
        if (Objects.nonNull(root)) {
            root.setUserId(userId);
            root.setModifiedTime(DateTimeUtil.toMilli(LocalDateTime.now()));
            userInfoMapper.updateByPrimaryKeySelective(root);
            return;
        }
        UserSocialInfo socialInfo = ReflectionUtil.checkAndSetFieldValue(UserSocialInfo.class, fieldName, fieldVal);
        if (Objects.nonNull(socialInfo)) {
            socialInfo.setUserId(userId);
            socialInfo.setModifiedTime(DateTimeUtil.toMilli(LocalDateTime.now()));
            userSocialInfoMapper.updateByPrimaryKeySelective(socialInfo);
            return;
        }
    }

}
